
# -------------QT-------------

from io import StringIO
import os
from Bilibili import CBilibili
from datetime import time
import sys
from PyQt5.QtCore import QFile, QPropertyAnimation, QSignalBlocker, QSize, QTime, QTimer, Qt
from PyQt5.QtGui import QBrush, QCursor, QMovie, QPalette, QPixmap
from PyQt5.QtWidgets import QApplication, QDialog, QLabel, QMainWindow, QWidget
from UI.Ui_MainWindow import *
from UI.Ui_Update_UI import *
from UI.Ui_msgBox import *

# -------------QT-------------




# -------------Playable-------------

import update_module

# -------------Playable-------------




class MessageBox(QDialog, Ui_Form):
    def __init__(self):
        super(MessageBox, self).__init__()
        self.setupUi(self)
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
        #self.setAttribute(QtCore.Qt.WA_TranslucentBackground)  # 设置窗口背景透明
        self.btn_close.clicked.connect(self.close)

    def setText(self,msg):
        _translate = QtCore.QCoreApplication.translate
        self.textEdit.setHtml(_translate("Form", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Fira Code\'; font-size:14pt; font-weight:600; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'SimSun\'; font-weight:400; color:#00aaff;\">%s</span></p>\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><img src=\":/新前缀/bgImg2.jpg\" width=\"112\" height=\"72\" /></p></body></html>"%msg))

    fadeIn_animation = None
    def showEvent(self, a0: QtGui.QShowEvent) -> None:

        self.fadeOut_animation = None     
        if self.fadeIn_animation is None:
            self.fadeIn_animation = QPropertyAnimation(self, b'windowOpacity')
            self.fadeIn_animation.setDuration(500)
            self.fadeIn_animation.setStartValue(0)
            self.fadeIn_animation.setEndValue(1)
            self.fadeIn_animation.finished.connect(self.show)
            self.fadeIn_animation.start()
            a0.ignore()

    fadeOut_animation = None
    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:
        self.fadeIn_animation = None
        if self.fadeOut_animation is None:
            self.fadeOut_animation = QPropertyAnimation(self, b'windowOpacity')
            self.fadeOut_animation.setDuration(500)
            self.fadeOut_animation.setStartValue(1)
            self.fadeOut_animation.setEndValue(0)
            self.fadeOut_animation.finished.connect(self.close)
            self.fadeOut_animation.start()
            a0.ignore()

class ChildWindow(QDialog, Ui_Dialog):
    def __init__(self):
        super(ChildWindow, self).__init__()
        self.setupUi(self)

        gif = QMovie('res/1000.gif')
        self.label.setMovie(gif)
        gif.start()

    def setText(self, _text):
        _translate = QtCore.QCoreApplication.translate
        self.textEdit.setHtml(_translate("Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                                         "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                                         "p, li { white-space: pre-wrap; }\n"
                                         "</style></head><body style=\" font-family:\'SimSun\'; font-size:24pt; font-weight:400; font-style:normal;\">\n"
                                         "<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" color:#ffffff;\">%s</span></p></body></html>" % _text))

    timer = None
    animation = None

    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:
        if self.timer:
            self.timer.stop()
        if self.animation is None:
            self.animation = QPropertyAnimation(self, b'windowOpacity')
            self.animation.setDuration(400)
            self.animation.setStartValue(1)
            self.animation.setEndValue(0)
            self.animation.finished.connect(self.close)
            self.animation.start()
            a0.ignore()

class MainWindow(QMainWindow, Ui_MainWindow):

    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:
        if self.animation is None:
            self.animation = QPropertyAnimation(self, b'windowOpacity')
            self.animation.setDuration(400)
            self.animation.setStartValue(1)
            self.animation.setEndValue(0)
            self.animation.finished.connect(self.close)
            self.animation.start()
            a0.ignore()

    # -------------重写拖动-------------

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.m_flag = True
            self.m_Position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置
            event.accept()
            self.setCursor(QCursor(Qt.OpenHandCursor))  # 更改鼠标图标

    def mouseMoveEvent(self, QMouseEvent):
        if Qt.LeftButton and self.m_flag:
            self.move(QMouseEvent.globalPos() - self.m_Position)  # 更改窗口位置
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        self.m_flag = False
        self.setCursor(self.__defaultCursor)

    # -------------重写拖动-------------

    __update_ui = None
    __flag = True
    __timer = None
    __defaultCursor = None
    __bilibili = None

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.__update_ui = ChildWindow()
        self.animation = None

        # 1. 创建光标的图像，参数为光标的相对位置（本文将光标存在工程目录的res文件夹下）
        pixmap = QPixmap('res/mouse.png')
        # 2. 创建一个新的图像，为原素材缩小到15*20大小
        pixmap = pixmap.scaled(24, 24)
        # 3. 将新光标对象传入鼠标对象中，并将鼠标锚点设为中心偏上
        self.__defaultCursor = QCursor(pixmap, 0, 0.8)
        # 4. 设置当前窗口光标
        self.setCursor(self.__defaultCursor)

        # 设置按钮图片
        img_path = 'res/closeWindowIcon.png'
        self.btn_close.setStyleSheet("QPushButton{\n"
                                     "background-image: url(\"%s\");\n"
                                     "background-position:center;\n"
                                     "background-repeat:no-repeat;\n"
                                     "}" % img_path)
        img_path = 'res/minModeIcon.png'
        self.btn_min.setStyleSheet("QPushButton{\n"
                                   "background-image: url(\"%s\");\n"
                                   "background-position:center;\n"
                                   "background-repeat:no-repeat;\n"
                                   "}" % img_path)
        # 按钮事件
        self.btn_min.clicked.connect(self.showMinimized)
        self.btn_close.clicked.connect(self.close)

        # 右下角动画
        gif = QMovie('res/1001.gif')
        self.__gif = gif
        gif.setScaledSize(QSize(self.width(), self.height()))
        self.rb_log.setMovie(gif)
        self.rb_log.setGeometry(QtCore.QRect(
            0, 0, self.width(), self.height()))

        # 弹幕
        self.__bilibili = CBilibili(self.msg_0)
        # self.enterBusyState()
        self.box_path.textChanged.connect(self.editchange)

        #检查路径按钮
        self.pushButton.clicked.connect(self.checkPath)

        self.__msgBox = MessageBox()
    def checkPath(self):
        self.__msgBox.show()
        url = self.box_path.toPlainText()
        if url.find('file:///') and  url.find('web-mobile') and os.path.isdir(url):
            self.__msgBox.setText('Correct cocosCreator web-mobile path')
        else:
            self.__msgBox.setText('The specified file is not the correct web-mobile')

    def editchange(self):
        if 0 == self.box_path.toPlainText().find('file:///'):
            self.box_path.setText(
                self.box_path.toPlainText().replace('file:///', ''))

    def enterBusyState(self):

        self.__gif.start()
        self.rb_log.setVisible(True)
        self.__bilibili.show()

    def enterIdleState(self):

        self.__gif.stop()
        self.rb_log.setVisible(False)
        self.__bilibili.hide()

    __gif = None

    def convertFinish(self):

        # 停止过场动画
        self.__gif.stop()
        self.rb_log.setVisible(False)

    def show(self) -> None:
        super().show()
        self.__update_ui.show()
        self.__update_ui.setText("版本更新中...")

        self.__timer = QTimer(self)
        self.__timer.start(1000)
        self.__timer.timeout.connect(self.timeout_slot)

        update_module.pull(self.pullComplete)

    def pullComplete(self, flag):
        self.__timer.stop()
        if flag:
            self.__update_ui.setText("最新资源拉取完成 !!!")
        else:
            self.__update_ui.setText("欢迎回来 !!!")

        self.__timer.timeout.disconnect(self.timeout_slot)
        self.__timer.timeout.connect(self.__update_ui.close)
        self.__timer.start(1000)

    def timeout_slot(self):
        self.__flag = not self.__flag
        if self.__flag:
            self.__update_ui.setText("版本更新中...")
        else:
            self.__update_ui.setText("稍作等待...")




if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    # 主窗口大小调整
    # desktop = QApplication.desktop()
    # r = myWin.width() / myWin.height()
    # h = desktop.height() * 0.618
    # w = h * r
    # myWin.resize(w,h)
    w = mainWindow.width()
    h = mainWindow.height()
    mainWindow.setFixedSize(w, h)

    # 背景适配
    p = QtGui.QPalette()
    pix = QtGui.QPixmap('res/bgImg.jpg')
    pix = pix.scaled(w, h)
    p.setBrush(QPalette.Background, QBrush(pix))
    mainWindow.setPalette(p)

    # 无边框
    mainWindow.setWindowFlag(QtCore.Qt.FramelessWindowHint)
    mainWindow.setWindowOpacity(0.9)  # 设置窗口透明度
    mainWindow.setAttribute(QtCore.Qt.WA_TranslucentBackground)  # 设置窗口背景透明

    mainWindow.show()
    sys.exit(app.exec_())
